package com.yixing.tech.common.tcp.client;

import com.yixing.tech.common.tcp.channel.ChannelInit;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;

import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyTcpClient {

    private final ChannelInit channelInit;

    private Channel channel;

    private EventLoopGroup workerGroup;

    private Bootstrap bootstrap;

    private String remoteHost;
    private Integer remotePort;

    public NettyTcpClient(ChannelInit channelInit) {
        this.channelInit = channelInit;

        this.workerGroup = new NioEventLoopGroup();
    }

    public void connect(String host, Integer port) throws Exception {
        remoteHost = host;
        remotePort = port;

        this.bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(channelInit)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.TCP_NODELAY, false)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_SNDBUF, 128)
                .option(ChannelOption.SO_RCVBUF, 128);

        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
        channel = channelFuture.channel();
    }

    public void disconnect() throws InterruptedException {
        if(channel != null) {
            channel.close();
        }
        workerGroup.shutdownGracefully();
    }

    public void reconnect() throws Exception {
        connect(remoteHost, remotePort);
    }

    public void send(String message) throws Exception {
        if(channel.isOpen()) {
            if(channel.isWritable()) {
                channel.writeAndFlush(message);
            }else {
                throw new RuntimeException("channel通道与服务端连接已断开");
            }
        }else {
            throw new RuntimeException("channel通道与服务端连接已断开");
        }
    }

    public void setRemoteHostAndPort(String host, Integer port) {
        this.remoteHost = host;
        this.remotePort = port;
    }
    
    public Channel getChannel() {
        return channel;
    }
}
